package com.exam.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.exam.pojo.Department;
import com.exam.pojo.Select;
import com.exam.pojo.User;
import com.exam.service.impl.DepartmentServiceImpl;
import com.exam.service.impl.QuestionServiceImpl;
import com.exam.service.impl.UserServiceImpl;
import com.exam.vo.ResultData;
import com.exam.vo.examEnum.ResultCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * Created by 23115 on 2021/8/2 22:33
 */
@RestController
@RequestMapping(value = "/admin")
@Slf4j
@Api(tags = "超级管理员权限相关的接口")
public class AdminController extends BaseController{
    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private DepartmentServiceImpl departmentService;

    //jackson
    ObjectMapper mapper = new ObjectMapper();


    @GetMapping("/getUser")
    @ApiOperation("获取用户信息pageNo,pageSize")
    public ResultData getUser(@RequestParam(required = false) String keyWord,
                                            Integer pageNo, Integer pageSize) throws InterruptedException {
        //参数一是当前页，参数二是每页个数
        IPage<User> userPage = new Page<>(pageNo, pageSize);
        //查询条件account或者name
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (!Objects.equals(keyWord, null)) {
            wrapper.like("account", keyWord).or().like("name", keyWord);
        }
//        if (!Objects.equals(keyWord, null)){
//
//        }
        userPage = userService.page(userPage, wrapper);
        Map<String, Object> map = new HashMap<>();
        List<User> users = userPage.getRecords();
        map.put("total",userPage.getTotal());
        map.put("userList",users);
        return new ResultData(map);
    }


    @GetMapping("/handleUser")
    @ApiOperation("type=1(启用) 2(禁用) 3(删除) userIds(需要操作的用户id)")
    public ResultData<String> handleUser(@RequestParam Integer type,@RequestParam String userIds) {
        System.out.println(type);
        System.out.println(userIds);
        //转换成数组 需要操作的用户的id数组
        String[] ids = userIds.split(",");
        if (type == 1) {//启用
            for (String id : ids) {
                User user = userService.getById(Integer.parseInt(id));
                user.setActive("1");
                userService.update(user, new UpdateWrapper<User>().eq("id", Integer.parseInt(id)));
            }
            return new ResultData<>();
        } else if (type == 2) {//禁用
            for (String id : ids) {
                User user = userService.getById(Integer.parseInt(id));
                user.setActive("0");
                userService.update(user, new UpdateWrapper<User>().eq("id", Integer.parseInt(id)));
            }
            return new ResultData<>();
        } else if (type == 3) {//删除
            for (String id : ids) {
                userService.removeById(Integer.parseInt(id));
            }
            return new ResultData<>();
        } else return ResultData.error(ResultCode.BAD_REQUEST.getCode(),ResultCode.BAD_REQUEST.getMsg());
    }

    @PostMapping("/addUser")
    @ApiOperation("管理员用户新增用户")
    public ResultData<Map<String,Boolean>>  addUser(@RequestBody User user) throws NoSuchAlgorithmException {
        Map<String, Boolean> hashMap = new HashMap();
        if(user.getActive()==null){
            user.setActive("0");
        }
        if (user.getPassword()==null){
            user.setPassword("Fnst.1234");
        }
        boolean save=userService.save(user);
        if (save) {
            hashMap.put("msg", save);
            return ResultData.success(hashMap);
        }
        return ResultData.error(ResultCode.INTERNAL_ERROR.getCode(), ResultCode.INTERNAL_ERROR.getMsg());
    }
    /**
     * 导入用户
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/excelImport")
    public ResultData excelImportUser(@RequestParam("file") MultipartFile file) throws IOException {
        boolean flag=userService.excelImportStu(file);
        if (flag){
            return ResultData.success(flag);
        }
        return ResultData.error(ResultCode.INTERNAL_ERROR.getCode(), ResultCode.INTERNAL_ERROR.getMsg());
    }
    @PostMapping("/updateUser")
    public ResultData<Map<String,Boolean>> updateUser(@RequestBody User user) {
        Map<String,Boolean> hp = new HashMap();
        boolean a=userService.updateById(user);
        if (a) {
            hp.put("msg", a);
            return ResultData.success(hp);
        }
        return ResultData.error(ResultCode.BAD_REQUEST.getCode(), ResultCode.BAD_REQUEST.getMsg());
    }

    @GetMapping("/getDepartment")
    @ApiOperation("查询部门信息")
    public ResultData<Object> getDepartment() {
        List<Department> userRoles = departmentService.list();
        return new ResultData<>(userRoles);
    }
    //删除部门
    @DeleteMapping("/dept/{deptid}")
    @ApiOperation("删除部门信息")
    public ResultData<Map<String,Boolean>> deleteDept(@PathVariable String deptid) {
        Map<String,Boolean> hp=new HashMap();
        String[] ids=deptid.split(",");
        boolean flag=false;
        for (String id:ids){
            flag=departmentService.removeById(id);
        }
        if (flag) {
            hp.put("msg", flag);
            return ResultData.success(hp);
        }
        return ResultData.error(ResultCode.BAD_REQUEST.getCode(), ResultCode.BAD_REQUEST.getMsg());
    }
    @PostMapping("/addDept")
    @ApiOperation("管理员用户新增部门")
    public ResultData<Map<String,Boolean>>  addDept(@RequestBody Department departmentInfo) throws NoSuchAlgorithmException {
        System.out.println("dept:"+departmentInfo);
        Map<String, Boolean> hashMap = new HashMap();
        boolean save=departmentService.save(departmentInfo);
        if (save) {
            hashMap.put("msg", save);
            return ResultData.success(hashMap);
        }
        return ResultData.error(ResultCode.INTERNAL_ERROR.getCode(), ResultCode.INTERNAL_ERROR.getMsg());
    }
    @PostMapping("/updateDept")
    public ResultData<Map<String,Boolean>> updateUser(@RequestBody Department dept) {

        Map<String,Boolean> hp = new HashMap();
        boolean a=departmentService.updateById(dept);
        if (a) {
            hp.put("msg", a);
            return ResultData.success(hp);
        }
        return ResultData.error(ResultCode.BAD_REQUEST.getCode(), ResultCode.BAD_REQUEST.getMsg());
    }

}
